#include "HTTPHandler.h"
#include "HTTPRequest.h"
#include "File.h"
#include "Socket.h"
#include "StringUtil.h"
#include "JarvCore.h"
SK
HTTPHandler::HTTPHandler (JarvCore *core)
:core(core)
{

}

HTTPHandler::~HTTPHandler()
{

}

void HTTPHandler::processJarvCommand (const String& postData)
{
	core->speak (postData);
}



void HTTPHandler::processRequest (const String& requestData, Socket *soc, HTTPRequest& req, String& postData)
{
	//this->req = HTTPRequest (requestData, soc);

	if (!req.isValid ())
	{
		return;
	}

	String file = "c:\\jarv" + req.file;
	File fle;
	bool fileFound;

	if (req.fileType == HTTP_FILE_TYPE_JARVCMD)
	{
		processJarvCommand(postData);
		return;
	}
	
	if (req.fileMode == HTTP_FILE_MODE_TEXT)
		fileFound = fle.open (file.c_str(), "rb");
	else
		fileFound = fle.open (file.c_str(), "rb");

	String response;

	if (fileFound)
	{

			int size = fle.getSize();
			response = "HTTP/1.1 200 OK\r\n";
			response += "host: " + req.host + "\r\n";
			response += "Content-Type: " + req.fileMIME + "; charset=utf-8\r\n";
			response += "Content-Length: " + StringUtil::toString (size);
			response += "\r\n\r\n";
			
			byte *bu = new byte [size];
			fle.read (bu, size);
			fle.close();

			soc->send (response);
			soc->sendAll(bu,size);

			delete [] bu;
	}
	else
	{
		response = "HTTP/1.1 404 Not Found\r\n";
		response += "host: " + req.host + "\r\n";
		response += "\r\n";
		soc->send (response);
		soc->close();
	}
	
}



EK